<?php

namespace apiend\modules\mall\models;

use Yii;
use common\models\shop\ShopCart;

/**
 * 加入购物车模型
 * 
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class CartUpdateForm extends \common\base\Model {

    /**
     * @var integer 下单用户ID
     */
    public $user_id;

    /**
     * @var integer SPUID
     */
    public $product_id;

    /**
     * @var string SKUID:数量,
     */
    public $list;

    /**
     * @var array [SKUID:数量]
     */
    private $_goods = [];

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['product_id', 'list'], 'required'],
            [['user_id', 'product_id'], 'integer'],
            [['list'], 'string'],
            [['list'], 'validateList'],
        ];
    }

    /**
     * 校验加入购物车的条目信息
     */
    public function validateList($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $goods = [];
        $array = array_filter(explode(',', $this->$attribute));
        foreach ($array as $item) {
            $g = explode(':', $item);
            if (count($g) !== 2) {
                continue;
            }
            $goods[$g[0]] = $g[1];
        }
        if (empty($goods)) {
            $this->addError($attribute, '请选择商品规格信息');
        } else {
            $this->_goods = $goods;
        }
    }

    /**
     * 获取所选规格列表
     * @return array
     */
    public function getGoods() {
        return $this->_goods;
    }

    /**
     * 加入购物车
     * @return boolean
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('加入失败');
        }
        $goods = $this->getGoods();

        $transaction = Yii::$app->db->beginTransaction();
        try {
            ShopCart::deleteAll([
                'user_id' => $this->user_id,
                'product_id' => $this->product_id,
            ]);
            foreach ($goods as $gid => $num) {
                $model = ShopCart::findOrNew([
                    'user_id' => $this->user_id,
                    'product_id' => $this->product_id,
                    'goods_id' => $gid,
                    'deleted_at' => 0,
                ]);
                $model->num = $num;
                $model->status = ShopCart::STATUS_CHECKED;
                if (!$model->save()) {
                    throw new Exception($model->getErrorMsg());
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            return $this->dumpError($e->getMessage(), false);
        }
        $searchModel = new CartSearch();
        $searchModel->user_id = $this->user_id;
        $searchModel->product_id = $this->product_id;
        return $searchModel->searchItem();
    }

}
